package mathsys;

import java.io.*;
import java.util.*;

public class MathExerciseGeneratorV5 {
    // 存储已生成的算式，用于去重
    private static Set<String> generatedExpressions = new HashSet<>();

    // 生成指定范围内的随机整数
    private static int getRandomNumber(int min, int max) {
        Random random = new Random();
        return random.nextInt(max - min + 1) + min;
    }

    // 生成带答案的加减法算式（确保不重复）
    private static Map.Entry<String, Integer> generateUniqueExercise() {
        while (true) {
            int num1 = getRandomNumber(0, 100);
            int num2 = getRandomNumber(0, 100);
            int operator = getRandomNumber(0, 1); // 0:加法, 1:减法
            String expression;
            int result;

            if (operator == 0) { // 加法
                if (num1 + num2 > 100) continue;
                // 标准化加法表达式，避免3+5和5+3被视为不同
                if (num1 > num2) {
                    int temp = num1;
                    num1 = num2;
                    num2 = temp;
                }
                expression = num1 + " + " + num2;
                result = num1 + num2;
            } else { // 减法
                if (num1 < num2) continue;
                expression = num1 + " - " + num2;
                result = num1 - num2;
            }

            // 检查是否已存在该算式
            if (!generatedExpressions.contains(expression)) {
                generatedExpressions.add(expression);
                return new AbstractMap.SimpleEntry<>(expression, result);
            }
        }
    }

    // 生成HTML文件
    private static void generateHTML(List<Map.Entry<String, Integer>> exercises) {
        try (PrintWriter out = new PrintWriter(new FileWriter("math_exercises_v0.5.html"))) {
            out.println("<!DOCTYPE html>");
            out.println("<html lang=\"zh-CN\">");
            out.println("<head>");
            out.println("    <meta charset=\"UTF-8\">");
            out.println("    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
            out.println("    <title>加减法口算练习系统-v0.5</title>");
            out.println("    <style>");
            out.println("        * { box-sizing: border-box; margin: 0; padding: 0; }");
            out.println("        body { font-family: 'Segoe UI', Arial, sans-serif; max-width: 1400px; margin: 0 auto; padding: 20px; background-color: #f5f7fa; }");
            out.println("        .container { background-color: white; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); padding: 30px; }");
            out.println("        h1 { color: #2c3e50; text-align: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 2px solid #3498db; }");
            out.println("        .stats { text-align: center; color: #666; margin: 10px 0 25px; font-size: 1.1em; }");
            out.println("        .exercise-container { margin: 20px auto; display: grid;");
            out.println("            grid-template-columns: repeat(4, 1fr);"); /* 固定4列 */
            out.println("            gap: 20px; }");
            out.println("        .exercise { font-size: 18px; padding: 20px; border: 1px solid #e1e5e8;");
            out.println("            border-radius: 8px; background-color: white; transition: transform 0.2s, box-shadow 0.2s; }");
            out.println("        .exercise:hover { transform: translateY(-3px); box-shadow: 0 4px 12px rgba(0,0,0,0.08); }");
            out.println("        .addition { border-left: 4px solid #2ecc71; }");
            out.println("        .subtraction { border-left: 4px solid #3498db; }");
            out.println("        .number { font-weight: bold; color: #2c3e50; margin-right: 8px; }");
            out.println("        .expression { color: #34495e; }");
            out.println("        .input-group { margin: 15px 0; display: flex; align-items: center; gap: 10px; }");
            out.println("        input { width: 70px; padding: 10px; font-size: 16px; text-align: center;");
            out.println("            border: 1px solid #bdc3c7; border-radius: 4px; transition: border 0.3s; }");
            out.println("        input:focus { border-color: #3498db; outline: none; box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2); }");
            out.println("        .btn { padding: 8px 16px; font-size: 14px; border: none; border-radius: 4px; cursor: pointer; transition: background-color 0.3s; }");
            out.println("        .check-btn { background-color: #95a5a6; color: white; }");
            out.println("        .check-btn:hover { background-color: #7f8c8d; }");
            out.println("        .reset-btn { background-color: #f39c12; color: white; }");
            out.println("        .reset-btn:hover { background-color: #e67e22; }");
            out.println("        .feedback { margin-top: 12px; padding: 10px; border-radius: 4px; font-size: 14px; display: none; }");
            out.println("        .correct { background-color: #eafaf1; color: #27ae60; border: 1px solid #c8e6c9; display: block; }");
            out.println("        .incorrect { background-color: #fdedeb; color: #e74c3c; border: 1px solid #f8d7da; display: block; }");
            out.println("        .empty { background-color: #fef9e7; color: #f39c12; border: 1px solid #f5e79e; display: block; }");
            out.println("        .controls { text-align: center; margin: 30px 0; display: flex; justify-content: center; gap: 15px; flex-wrap: wrap; }");
            out.println("        .main-btn { padding: 12px 24px; font-size: 16px; }");
            out.println("        #submitAllBtn { background-color: #3498db; color: white; }");
            out.println("        #submitAllBtn:hover { background-color: #2980b9; }");
            out.println("        #resetAllBtn { background-color: #e74c3c; color: white; }");
            out.println("        #resetAllBtn:hover { background-color: #c0392b; }");
            out.println("        #regenerateBtn { background-color: #2ecc71; color: white; }");
            out.println("        #regenerateBtn:hover { background-color: #27ae60; }");
            out.println("        .footer { text-align: center; margin-top: 30px; color: #7f8c8d; font-size: 0.9em; }");
            out.println("        @media (max-width: 1200px) {");
            out.println("            .exercise-container { grid-template-columns: repeat(3, 1fr); }");
            out.println("        }");
            out.println("        @media (max-width: 900px) {");
            out.println("            .exercise-container { grid-template-columns: repeat(2, 1fr); }");
            out.println("        }");
            out.println("        @media (max-width: 600px) {");
            out.println("            .exercise-container { grid-template-columns: 1fr; }");
            out.println("            .controls { flex-direction: column; align-items: center; }");
            out.println("            .main-btn { width: 80%; }");
            out.println("        }");
            out.println("    </style>");
            out.println("    <script>");
            // 检查单个答案
            out.println("        function checkAnswer(index, correctAnswer) {");
            out.println("            const input = document.getElementById('answer_' + index);");
            out.println("            const feedback = document.getElementById('feedback_' + index);");
            out.println("            const userAnswer = input.value.trim();");
            out.println("");
            out.println("            // 禁用输入框防止再次修改");
            out.println("            input.disabled = true;");
            out.println("");
            // 清空之前的反馈样式
            out.println("            feedback.classList.remove('correct', 'incorrect', 'empty');");
            out.println("");
            out.println("            if (userAnswer === '') {");
            out.println("                feedback.textContent = '未填写答案，正确答案是: ' + correctAnswer;");
            out.println("                feedback.classList.add('empty');");
            out.println("            } else if (parseInt(userAnswer) === correctAnswer) {");
            out.println("                feedback.textContent = '答对了，真棒！';");
            out.println("                feedback.classList.add('correct');");
            out.println("            } else {");
            out.println("                feedback.textContent = '答错了，正确答案是: ' + correctAnswer;");
            out.println("                feedback.classList.add('incorrect');");
            out.println("            }");
            out.println("        }");
            out.println("");
            // 重置单个题目
            out.println("        function resetAnswer(index) {");
            out.println("            const input = document.getElementById('answer_' + index);");
            out.println("            const feedback = document.getElementById('feedback_' + index);");
            out.println("");
            out.println("            // 清空输入和反馈");
            out.println("            input.value = '';");
            out.println("            input.disabled = false;");
            out.println("            feedback.textContent = '';");
            out.println("            feedback.classList.remove('correct', 'incorrect', 'empty');");
            out.println("        }");
            out.println("");
            // 批量提交所有答案
            out.println("        function submitAllAnswers() {");
            out.println("            const total = " + exercises.size() + ";");
            out.println("            let correctCount = 0;");
            out.println("            for (let i = 0; i < total; i++) {");
            out.println("                const input = document.getElementById('answer_' + i);");
            out.println("                const correctAnswer = parseInt(document.getElementById('correct_' + i).value);");
            out.println("                const userAnswer = input.value.trim();");
            out.println("");
            out.println("                if (userAnswer !== '' && parseInt(userAnswer) === correctAnswer) {");
            out.println("                    correctCount++;");
            out.println("                }");
            out.println("                checkAnswer(i, correctAnswer);");
            out.println("            }");
            out.println("            alert('提交完成！共' + total + '题，答对' + correctCount + '题，正确率：' + Math.round((correctCount/total)*100) + '%');");
            out.println("        }");
            out.println("");
            // 重置所有题目
            out.println("        function resetAllAnswers() {");
            out.println("            if (confirm('确定要重置所有答案吗？当前输入将被清空')) {");
            out.println("                const total = " + exercises.size() + ";");
            out.println("                for (let i = 0; i < total; i++) {");
            out.println("                    resetAnswer(i);");
            out.println("                }");
            out.println("            }");
            out.println("        }");
            out.println("");
            // 重新生成题目
            out.println("        function regenerateExercises() {");
            out.println("            if (confirm('确定要生成新的50道题目吗？当前进度将丢失')) {");
            out.println("                window.location.href = 'math_exercises_v0.5.html';");
            out.println("            }");
            out.println("        }");
            out.println("    </script>");
            out.println("</head>");
            out.println("<body>");
            out.println("    <div class=\"container\">");
            out.println("        <h1>加减法口算练习系统-v0.5</h1>");

            // 统计加减法数量
            long additionCount = exercises.stream()
                    .filter(e -> e.getKey().contains("+"))
                    .count();
            long subtractionCount = exercises.size() - additionCount;

            out.println("        <div class=\"stats\">");
            out.println("            共" + exercises.size() + "题（加法：" + additionCount + "题，减法：" + subtractionCount + "题）");
            out.println("        </div>");

            out.println("        <div class=\"exercise-container\">");

            // 循环生成习题
            int index = 0;
            for (Map.Entry<String, Integer> exercise : exercises) {
                String expression = exercise.getKey();
                int answer = exercise.getValue();
                String typeClass = expression.contains("+") ? "addition" : "subtraction";

                out.println("            <div class=\"exercise " + typeClass + "\">");
                out.println("                <span class=\"number\">" + (index + 1) + ". </span>");
                out.println("                <span class=\"expression\">" + expression + " = </span>");
                out.println("                <div class=\"input-group\">");
                out.println("                    <input type=\"number\" id=\"answer_" + index + "\" placeholder=\"?\">");
                out.println("                    <button class=\"btn check-btn\" onclick=\"checkAnswer(" + index + ", " + answer + ")\">检查</button>");
                out.println("                    <button class=\"btn reset-btn\" onclick=\"resetAnswer(" + index + ")\">重置</button>");
                out.println("                </div>");
                out.println("                <div id=\"feedback_" + index + "\" class=\"feedback\"></div>");
                // 隐藏的正确答案存储
                out.println("                <input type=\"hidden\" id=\"correct_" + index + "\" value=\"" + answer + "\">");
                out.println("            </div>");
                index++;
            }

            out.println("        </div>");

            // 控制按钮区域
            out.println("        <div class=\"controls\">");
            out.println("            <button id=\"submitAllBtn\" class=\"btn main-btn\" onclick=\"submitAllAnswers()\">提交所有答案</button>");
            out.println("            <button id=\"resetAllBtn\" class=\"btn main-btn\" onclick=\"resetAllAnswers()\">重置所有题目</button>");
            out.println("            <button id=\"regenerateBtn\" class=\"btn main-btn\" onclick=\"regenerateExercises()\">生成新题目</button>");
            out.println("        </div>");

            out.println("        <div class=\"footer\">");
            out.println("            加减法口算练习系统 &copy; " + Calendar.getInstance().get(Calendar.YEAR));
            out.println("        </div>");
            out.println("    </div>");
            out.println("</body>");
            out.println("</html>");

            System.out.println("习题已生成，请打开 math_exercises_v0.5.html 文件查看");
        } catch (IOException e) {
            System.err.println("生成HTML文件时出错: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        int totalCount = 50;
        if (totalCount < 2) {
            System.err.println("题目数量不能少于2道");
            return;
        }

        List<Map.Entry<String, Integer>> exercises = new ArrayList<>();
        generatedExpressions.clear();

        // 确保至少有1道加法和1道减法
        while (true) {
            Map.Entry<String, Integer> exercise = generateUniqueExercise();
            if (exercise.getKey().contains("+")) {
                exercises.add(exercise);
                break;
            }
        }
        while (true) {
            Map.Entry<String, Integer> exercise = generateUniqueExercise();
            if (exercise.getKey().contains("-")) {
                exercises.add(exercise);
                break;
            }
        }

        // 生成剩余题目
        for (int i = 2; i < totalCount; i++) {
            exercises.add(generateUniqueExercise());
        }

        // 打乱题目顺序
        Collections.shuffle(exercises);

        // 生成HTML页面
        generateHTML(exercises);
    }
}